//
//  LZComposeController.swift
//  Weibo
//
//  Created by lzing on 16/3/30.
//  Copyright © 2016年 lzing. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class LZComposeController: UIViewController {

    //MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        // 设置导航栏
        setupNavigationBar()
        // 设置textView
        setupTextView()
        // 设置照片选择器
        setupPhotoSelector()
        // 设置工具条
        setupToolBar()
        // 设置长度提示label
        setupLengthTip()
        // 监听键盘状态改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        // 移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 成为第一响应者
        textView.becomeFirstResponder()
    }
    
    //MARK: - keyboardFrameChange
    @objc private func keyboardWillChangeFrame(notification:NSNotification) {
        /*
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1]
        */
        // 动画时间
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        // 目标frame
        let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue ?? CGRectZero
        // 计算toolbar间距
        let margin = -(UIScreen.height - keyboardFrame.origin.y)
        // 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(margin)
        }
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    //MARK: - setupNavigationBar
    private func setupNavigationBar() {
        // 左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnDidClick")
        // 右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendBtnDidClick")
        // 发送按钮禁用
        navigationItem.rightBarButtonItem?.enabled = false
        // 设置titleView
        setupTitleView()
    }
    
    //MARK: - setupTextView
    private func setupTextView() {
        textView.delegate = self
        // 添加textView
        view.addSubview(textView)
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    
    //MARK: - setupPhotoSelector
    private func setupPhotoSelector() {
        // 添加控件
        view.addSubview(photoSelectorVC.view)
        addChildViewController(photoSelectorVC)
        // 添加约束
        photoSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.right.left.equalTo(view)
            make.height.equalTo(view).multipliedBy(0.6)
            // 将照片选择器view往下偏移
            make.bottom.equalTo(view).offset(UIScreen.height * 0.6)
        }
    }
    
    //MARK: - setupTitleView
    private func setupTitleView() {
        let prefix = "发微博"
        if let name = LZUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name {
            // title文本
            let text = prefix + "\n" + name
            let label = UILabel()
            // 设置label属性
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.textAlignment = NSTextAlignment.Center
            label.numberOfLines = 0
            // 设置文本属性
            let attributeText = NSMutableAttributedString(string: text)
            let nameRange = (text as NSString).rangeOfString(name)
            attributeText.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName : UIFont.systemFontOfSize(11)], range: nameRange)
            label.attributedText = attributeText
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            navigationItem.title = prefix
        }
    }
    
    //MARK: - setupToolBar
    private func setupToolBar() {
        // 添加toolBar
        view.addSubview(toolBar)
        // 约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
        // 创建空数组
        toolBar.items = [UIBarButtonItem]()
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            // 创建barButtonItem
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            toolBar.items?.append(item)
            // 在按钮后面添加弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 移除弹簧
        toolBar.items?.removeLast()
    }
    
    //MARK: - setupLengthTip
    private func setupLengthTip() {
        // 添加LengthTipLabel
        view.addSubview(statusLengthTipLabel)
        // 添加约束
        statusLengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view).offset(-5)
            make.bottom.equalTo(toolBar.snp_top).offset(-5)
        }
    }
    
    //MARK: - BtnClick
    ///  取消按钮点击事件
    @objc private func cancelBtnDidClick() {
        SVProgressHUD.dismiss()
        // 退出第一响应者
        textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///  发送按钮点击事件
    @objc private func sendBtnDidClick() {
        // 获取输入文本
        let status = textView.emoticonText()
        // 判断是否超出最大长度
        if LZComposeVCStatusMaxLength - status.characters.count < 0 {
            SVProgressHUD.showErrorWithStatus("微博内容超出最大长度")
            return
        }
        // 获取用户选择的第一张图片
        let image = photoSelectorVC.photos.first
        // 发微博
        SVProgressHUD.showWithStatus("正在发送微博", maskType: SVProgressHUDMaskType.Gradient)
        LZStatusView.sharedStatusView.sendStatus(status, image : image) { (error) -> () in
            if error != nil {
                LZPrint(msg: "发送微博失败")
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                return
            }
            // 发送成功
            SVProgressHUD.showSuccessWithStatus("发送微博成功")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.cancelBtnDidClick()
            })
        }
    }
    
    @objc private func picture() {
        // 偏移照片选择器
        photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(0)
        }
        UIView.animateWithDuration(LZDefaultDuration) { [weak self] () -> Void in
            self?.view.layoutIfNeeded()
        }
    }
    
    @objc private func trend() {
    
    }
    
    @objc private func mention() {
    
    }
    
    @objc private func add() {
        
    }
    
    ///  表情键盘
    @objc private func emoticon() {
        // 退出键盘
        textView.resignFirstResponder()
        // 设置键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        // 弹出键盘
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { [weak self] () -> Void in
            self?.textView.becomeFirstResponder()
        }
    }
    
    //MARK: - lazy
    /// 工具条
    private lazy var toolBar : UIToolbar = UIToolbar()
    ///  textView
    private lazy var textView : LZPlaceholderTextView = {
        let textView = LZPlaceholderTextView()
        // 设置textView
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        textView.backgroundColor = UIColor.whiteColor()
        // 设置弹簧效果
        textView.alwaysBounceVertical = true
        // 拖拽时键盘隐藏
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.placeholdText = "分享新鲜事........."
        textView.delegate = self
        return textView
    }()
    /// 长度提示的label
    private lazy var statusLengthTipLabel : UILabel = {
        let statusLengthTipLabel = UILabel()
        statusLengthTipLabel.font = UIFont.systemFontOfSize(11)
        statusLengthTipLabel.textColor = UIColor.lightGrayColor()
        statusLengthTipLabel.text = String(LZComposeVCStatusMaxLength)
        return statusLengthTipLabel
    }()
    /// 表情键盘
    private lazy var emoticonKeyboard: LZEmoticonKeyboard = {
        let keyboard = LZEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    /// 照片选择器
    private lazy var photoSelectorVC : PhotoSelectorController = PhotoSelectorController()
}

extension LZComposeController : UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        // 有文字就可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
//        LZPrint(msg: "textView.emoticonText(): \(textView.emoticonText())")
        // 获取文字长度
        let length = textView.emoticonText().characters.count
        let left = LZComposeVCStatusMaxLength - length
        statusLengthTipLabel.text = String(left)
        // 设置颜色
        statusLengthTipLabel.textColor = left < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
